package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.config.PasswordConfig;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;



@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    AmqpTemplate amqpTemplate;
    @Autowired
    PasswordEncoder passwordEncoder;
    private static final String KEY_PREFIX="user:verify:code";
    @Override
    public void sendCode(String phone) {
        //健壮性判断手机号
        if (!RegexUtils.isPhone(phone)){
            throw new LyException(400,"参数有误");
        }
        //生成6位随机数
        String code = RandomStringUtils.randomNumeric(6);
        //放到缓存中
        redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5L,TimeUnit.MINUTES);
        //发送RabbitMQ消息到ly-sms
        HashMap<String, String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);
        //发送消息 3个条件            路由名              匹配规则         消息
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,map);

    }

    @Override
    @Transactional
    public void register(User user, String code) {
            //判断严重码是否正确
        String s = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (!StringUtils.equals(code,s)){
            throw new LyException(400,"验证码错误");
        }
       //为了用户的安全进行密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //保存
        save(user);
    }

    @Override
    public UserDTO queryUserByPhoneAndPassword(String username, String password) {
        //通过用户名查询用户
        User user = query().eq("username", username).one();
        if (user==null){
            throw new LyException(400,"用户名或密码错误");
        }
        //校验密码 使用工具判断 底层是把传过来的密码进行同样加密 然后和数据库中的比较
        if (!passwordEncoder.matches(password,user.getPassword())){
            throw new LyException(400,"用户名或密码错误");
        }
        //转换类型返回
        return new UserDTO(user);
    }

    @Override
    public Boolean exists(String data, Integer type) {
        //健壮性判断
        if (type!=1&&type!=2){
            throw new LyException(400, "请求参数有误");
        }

        //条件查询
        return  query().eq(type==1,"username",data)
                .eq(type==2,"phone",data).count()==1;
    }
}
